package dao.impl;

import dao.SignInDao;
import domain.SignIn;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.JDBCUtils;
import utils.LyyLogUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SignInDaoImpl implements SignInDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    private QuerySignInDaysCallBack callBack;

    public void setCallBack(QuerySignInDaysCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public boolean addOne(SignIn signIn) throws Exception {
        String sql0="select count(*) from sign_in where userId=? and TO_DAYS(signTime)=TO_DAYS(NOW())";
        Integer count = 0;
        try {
            count = template.queryForObject(sql0, Integer.class, signIn.getUserId());
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
        }
        if(count>0){
            throw new Exception("签到失败，您今天已经签到过了，请明天再来！");
        }
        String sql="insert into sign_in values(?,?,?)";
        int update=0;
        try {
            update = template.update(sql, null, signIn.getUserId(), signIn.getSignTime());
        } catch (Exception e) {
            throw e;
        }finally {
            getSignInsByUserId(signIn.getUserId()+"");
        }
        return update!=0;
    }

    @Override
    public void getSignInsByUserId(String userId) throws Exception {
        String sql="select * from sign_in where userId=? order by signTime desc";
        List<SignIn> list1=null;
        try {
            list1 = template.query(sql, new BeanPropertyRowMapper<SignIn>(SignIn.class), userId);
        } catch (Exception e) {
            throw e;
        }finally {
            if(callBack!=null&&list1!=null&&list1.size()>0){
                List<Long> list2=new ArrayList<>();
                for (SignIn signIn : list1) {
                    Date signTime = signIn.getSignTime();
                    long time = signTime.getTime();
                    long day=time/(1000*60*60*24);
                    LyyLogUtil.logD("距离1970年1月1日的天数为："+day);
                    list2.add(day);
                }
                int days=1;//连续的天数
                for (int i = 0; i < list2.size(); i++) {
                    long num1 = list2.get(i);
                    if(i<list2.size()-1){
                        long num2 = list2.get(i + 1);
                        long sub=num2-num1;//差值
                        if(sub==1){
                            days++;
                        }else {
                            break;
                        }
                    }
                }
                callBack.onSuccess(days);
            }
        }
    }
}
